package com.yugu.park.system.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Api;
import com.yugu.park.annotation.Log;
import com.yugu.park.config.TokenService;
import com.yugu.park.exception.BizException;
import com.yugu.park.security.entity.LoginUser;
import com.yugu.park.security.entity.TSysUser;
import com.yugu.park.system.entity.SysUserEntity;
import com.yugu.park.system.service.SysUserService;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;

import com.yugu.enums.BusinessType;
import com.yugu.util.ResponseUtil;
import com.yugu.util.SearchPage;
import com.yugu.util.SecurityUtils;
import com.github.pagehelper.PageInfo;

/**
 * 用户信息表
 *
 * @author guxf
 * @email sjzyug@163.com
 * @date 2023-08-17 15:04:06
 */
@Api(tags = {"用户信息表"})
@RestController
@RequestMapping("system/user")
public class SysUserController {
    @Autowired
    private SysUserService service;
    @Value("${file.path}")
    private String savePath;
    @Resource
	private TokenService tokenService;

    /**
     * 列表
     */

    @ApiOperation(value="分页查询", notes="分页查询")
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public ResponseUtil.Result<PageInfo<SysUserEntity>> page (@RequestBody SearchPage<SysUserEntity> search){
        PageInfo<SysUserEntity> page = service.page(search);
        return ResponseUtil.addSuccess(page);
    }
	@ApiOperation(value="查看详情", notes="查看详情")
    @GetMapping("/{userId}")
    public ResponseUtil.Result<SysUserEntity> info(@PathVariable("userId") String userId){
		SysUserEntity sysUser = service.getById(userId);
        return ResponseUtil.addSuccess(sysUser);
    }
    @ApiOperation(value="新增", notes="新增")
    @RequestMapping(value="/save", method= RequestMethod.POST)
    public ResponseUtil.Result<Boolean> save(@RequestBody SysUserEntity sysUser){
		service.addOrUpdate(sysUser);
        return ResponseUtil.addSuccess(true);
    }
    @ApiOperation(value="新增或修改", notes="新增或修改")
    @RequestMapping(value="/addOrUpdate", method= RequestMethod.POST)
    public ResponseUtil.Result<Boolean> addOrUpdate(@RequestBody SysUserEntity sysUser){
		service.addOrUpdate(sysUser);
        return ResponseUtil.addSuccess(true);
    }
    /**
     * 修改
     */
    @ApiOperation(value="修改", notes="修改")
    @RequestMapping(value="/update", method = RequestMethod.PUT)
    public ResponseUtil.Result<Boolean> update(@RequestBody SysUserEntity sysUser){
		service.updateById(sysUser);
        return ResponseUtil.addSuccess(true);
    }
    @ApiOperation(value="批量删除", notes="批量删除")
    @RequestMapping(value="/delete", method = RequestMethod.DELETE)
    public ResponseUtil.Result<Boolean> delete(@RequestBody String[] userIds){
		service.removeByIds(Arrays.asList(userIds));
        return ResponseUtil.addSuccess(true);
    }
    @ApiOperation(value="删除", notes="删除")
    @RequestMapping(value="/{userId}", method = RequestMethod.DELETE)
    public ResponseUtil.Result<Boolean> delete(@PathVariable("userId") String userId){
    	service.removeByIds(Arrays.asList(userId.split(",")));
        return ResponseUtil.addSuccess(true);
    }
    /**
     * 修改
     */
    @ApiOperation(value="修改状态", notes="修改状态")
    @PutMapping(value="/changeStatus")
    public ResponseUtil.Result<Boolean> changeStatus(@RequestBody SysUserEntity sysUser){
		service.updateById(sysUser);
        return ResponseUtil.addSuccess(true);
    }
    @ApiOperation(value="查看详情", notes="查看详情")
    @GetMapping("/profile")
    public ResponseUtil.Result<TSysUser> profile(){
    	LoginUser loginUser = SecurityUtils.getLoginUser();
        return ResponseUtil.addSuccess(loginUser.getSysUser());
    }
    @ApiOperation(value="修改个人信息", notes="修改个人信息")
    @PutMapping("/profile")
    public ResponseUtil.Result<Boolean> updateProfile(@RequestBody SysUserEntity user){
//    	TSysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
    	LoginUser loginUser = SecurityUtils.getLoginUser();
    	TSysUser sysUser = loginUser.getSysUser();
    	sysUser.setSex(user.getSex());
    	sysUser.setEmail(user.getEmail());
    	sysUser.setPhonenumber(user.getPhonenumber());
    	service.addOrUpdate(SysUserEntity.builder().userId(sysUser.getUserId())
    		 .email(user.getEmail())
    		 .sex(user.getSex())
    		 .phonenumber(user.getPhonenumber()).build());
    	tokenService.refreshToken(loginUser);
        return ResponseUtil.addSuccess(true);
    }
    @Log(title = "修改密码", businessType = BusinessType.UPDATE)
    @ApiOperation(value="修改密码", notes="修改密码")
    @PutMapping("/profile/updatePwd")
    public ResponseUtil.Result<Boolean> updatePwd(String oldPassword, String newPassword){
    	LoginUser loginUser = SecurityUtils.getLoginUser();
     	TSysUser sysUser = loginUser.getSysUser();
         String password = sysUser.getPassword();
         if (!SecurityUtils.matchesPassword(oldPassword, password)){
        	 throw new BizException("修改密码失败，旧密码错误");
         }
         if (SecurityUtils.matchesPassword(newPassword, password)){
        	 throw new BizException("新密码不能与旧密码相同");
         }
         service.addOrUpdate(SysUserEntity.builder().userId(sysUser.getUserId())
        		 .password(new BCryptPasswordEncoder().encode(newPassword)).build());
        return ResponseUtil.addSuccess(true);
    }
    @Log(title = "修改头像", businessType = BusinessType.UPDATE)
    @ApiOperation(value="修改头像", notes="修改头像")
    @PostMapping("/profile/avatar")
    public ResponseUtil.Result<ModelMap> avatar(ModelMap modelMap,@RequestParam("file") MultipartFile file) throws IORuntimeException, IOException{
    	if (!file.isEmpty()) {
    		String originalFilename = file.getOriginalFilename();
    		String rootFilePath = savePath +"/avatar/"+ originalFilename;
    		FileUtil.writeBytes(file.getBytes(),rootFilePath);
    		String avatar ="/avatar/"+originalFilename;
//    		List<String> suffixList = Arrays.asList(new String[]{"jpg", "jpeg", "png"});
//            String fileName = file.getOriginalFilename();
//            String extName = file.getOriginalFilename().substring(fileName.indexOf(".") + 1);
//            String newName = UUID.randomUUID().toString() + "." + extName;
//            File newFile = new File(savePath, newName);
            modelMap.put("path", avatar);
            modelMap.put("planFlieId", UUID.randomUUID());
            LoginUser loginUser = SecurityUtils.getLoginUser();
         	TSysUser sysUser = loginUser.getSysUser();
         	sysUser.setAvatar(avatar);
         	
         	tokenService.refreshToken(loginUser);
            service.addOrUpdate(SysUserEntity.builder().userId(sysUser.getUserId())
            		.avatar(avatar).build());
    	}
        return ResponseUtil.addSuccess(modelMap);
    }

}
